package com.ad.aidai.fragments.select_school;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.ad.aidai.R;
import com.ad.aidai.base.BaseFragment;
import com.ad.aidai.common.widgets.WaveSideBar;
import com.jude.easyrecyclerview.decoration.DividerDecoration;
import com.orhanobut.logger.Logger;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 选择学校页面
 * <p>
 * Created by Yusoxn on 2017/1/23.
 */

public class SelectSchoolFragment extends BaseFragment implements SelectSchoolContract.View {

    @BindView(R.id.et_input_school)
    EditText etInputSchool;
    @BindView(R.id.rcv_select_school)
    RecyclerView rcvSelectSchool;
    @BindView(R.id.wsb_select_school_side_bar)
    WaveSideBar wsbSelectSchoolSideBar;

    /**
     * recycleView的布局管理器
     */
    private LinearLayoutManager mLinearLayoutManager;
    /**
     * 是否需要滚动
     */
    private boolean move = false;
    /**
     * 要置顶的项
     */
    private int mIndex = -1;

    private SelectSchoolContract.Presenter mPresenter;

    @Override
    protected void initLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_select_school, container, false);
        mView.setClickable(true);//防止点击穿透，底层的fragment响应上层点击触摸事件
    }

    @Override
    protected void initView() {
        etInputSchool.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mPresenter.searchSchool(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mLinearLayoutManager = new LinearLayoutManager((mActivity));
        //创建默认的线性LayoutManager
        rcvSelectSchool.setLayoutManager(mLinearLayoutManager);

        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        rcvSelectSchool.setHasFixedSize(true);

        //设置分割线
        DividerDecoration itemDecoration = new DividerDecoration(Color.parseColor("#E6E6E6"), 3, 0, 0);
        itemDecoration.setDrawLastItem(true);
        rcvSelectSchool.addItemDecoration(itemDecoration);

        //监听滚动事件
        rcvSelectSchool.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (move) {
                    int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
                    int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
                    int n = mIndex - firstItem;
                    //如果最后一项等于要置顶的项，说明滚动结束，所以在这里在添加滚动，使要置顶的项置顶
                    //因为recycleView的smoothScrollToPosition()方法是滚动到看得几就停止滚动，所以需要补充这个使其继续向上滚动
                    if (0 <= n && n < rcvSelectSchool.getChildCount() && lastItem == mIndex) {
                        move = false;
                        int top = rcvSelectSchool.getChildAt(n).getTop();
                        rcvSelectSchool.scrollBy(0, top);
                    }
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });

        wsbSelectSchoolSideBar.setOnSelectIndexItemListener(new WaveSideBar.OnSelectIndexItemListener() {
            @Override
            public void onSelectIndexItem(int index, String text) {
                //index为选中的字符的位置，text是选中的字符，这里要根据这两个参数获取对应的项在recycleView中的位置
                mIndex = mPresenter.getSelectItemPosition(index, text);
                if (mIndex == -1) {
                    return;
                }
                int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
                int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
                Logger.t(this.getClass().getSimpleName()).i(mIndex + "--" + text + "---" + firstItem + "---" +
                        lastItem);
                if (mIndex <= firstItem) {
                    //要置顶的项在当前屏幕第一项的前面，直接滚动即可
                    rcvSelectSchool.smoothScrollToPosition(mIndex);
                } else if (mIndex <= lastItem) {
                    //要置顶的项在当前屏幕中，获取离顶部的距离然后直接滚动即可
                    int top = rcvSelectSchool.getChildAt(mIndex - firstItem).getTop();
                    rcvSelectSchool.scrollBy(0, top);
                } else {
                    //要置顶的项在当前屏幕最后一项的后面，则先滚动到，这里滚动会到看得到时停止，所以需要让它继续向上滚动，所以设置move为true
                    rcvSelectSchool.smoothScrollToPosition(mIndex);
                    move = true;
                }
            }
        });
    }

    @Override
    protected void initData() {
        new SelectSchoolPresenter(mContext, this).subscribe();
        rcvSelectSchool.setAdapter(mPresenter.getAdapter());
        mPresenter.loadSchool();

    }

    @OnClick({R.id.iv_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                closeSoftInput(etInputSchool);
                onActivityBackPressed();
                break;

        }
    }

    /**
     * 关闭软键盘
     *
     * @param view 对应的EditText
     */
    public void closeSoftInput(View view) {
        InputMethodManager inputManager = (InputMethodManager) mActivity.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    @Override
    public void setPresenter(SelectSchoolContract.Presenter presenter) {
        this.mPresenter = presenter;
    }


    @Override
    public void searchFinish() {
        closeSoftInput(etInputSchool);
    }

    @Override
    public void itemClickExit() {
        getFragmentManager().popBackStack();
        closeSoftInput(etInputSchool);
    }

    @Override
    public boolean onActivityBackPressed() {
        getFragmentManager().popBackStack();
        return false;
    }
}
